//
//  UIColor+HEX.m
//  starspaceVR
//
//  Created by 曹端芹 on 17/9/23.
//  Copyright © 2017年 starspace. All rights reserved.
//

#import "UIColor+HEX.h"

@implementation UIColor (HEX)

+ (instancetype)colorWithHexString:(NSString *)hexString {
    
    NSString *colorString = [hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (colorString.length < 6) {
        return [UIColor clearColor];
    }
    if ([colorString hasPrefix:@"0X"]) {
        colorString = [colorString substringFromIndex:2];
    }
    if ([colorString hasPrefix:@"#"]) {
        colorString = [colorString substringFromIndex:1];
    }
    if (colorString.length != 6) {
        return [UIColor clearColor];
    }
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [colorString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [colorString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [colorString substringWithRange:range];
    
    
    unsigned int r,g,b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:(float)r / 255.0 green:(float)g / 255.0 blue:(float)b / 255.0 alpha:1.0];
}

+ (instancetype)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
    return [[self colorWithHexString:hexString] colorWithAlphaComponent:alpha];
}

+ (UIColor *)randomColor {
    
    NSArray *colorStrPol = @[@"009999", @"0099cc", @"0099ff", @"00cc99", @"00cccc", @"336699", @"3366cc", @"3366ff", @"339966", @"666666", @"666699", @"6666cc", @"6666ff", @"996666", @"996699", @"999900", @"999933", @"99cc00", @"99cc33", @"660066", @"669933", @"990066", @"cc9900", @"cc6600" , @"cc3300", @"cc3366", @"cc6666", @"cc6699", @"cc0066", @"cc0033", @"ffcc00", @"ffcc33", @"ff9900", @"ff9933", @"ff6600", @"ff6633", @"ff6666", @"ff6699", @"ff3366", @"ff3333"];
    
    NSMutableArray *colorPolM = [NSMutableArray array];
    for (NSString *colorStr in colorStrPol) {
        UIColor *color = [self colorWithHexString:colorStr];
        [colorPolM addObject:color];
    }
    
    return colorPolM[arc4random_uniform((uint32_t)colorPolM.count)];


}

@end
